<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2022/5/20
 * Time: 下午3:07
 */

namespace app\api\controller\v32;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\AstroChange as AstroChangeModel;
use app\common\cachemodel\Fortune;
use app\common\cachemodel\GoddessArea;
use app\common\cachemodel\lucky\AppLuckyTaskRecord;
use app\common\cachemodel\lucky\AppUserLuckyChangeRecord;
use app\common\cachemodel\lucky\AppUserLuckyInfo;
use app\common\cachemodel\Recode;
use app\common\lib\Util;
use think\Cache;
use think\Log;

/**
 * Class Component
 * @package app\api\controller\v32
 */
class Component extends Auth2
{
    protected $weekDay = [
        0 => '周日',
        1 => '周一',
        2 => '周二',
        3 => '周三',
        4 => '周四',
        5 => '周五',
        6 => '周六',
    ];

    /**
     * 每日运势小组件
     */
    public function today()
    {
        $app_type = $this->headers['app-type'];
        // 若登录则计算今日运势获取三星数据
        if ($this->user)
        {
            if (!$this->user['rid'])
            {
                if ($app_type === 'android')
                {
                    return show(200, '请点击前往添加档案', ['hint' => '', 'hint1' => '请点击前往添加档案']);
                }
                return show(0, '请点击前往添加档案', ['hint' => '']);
            }

            $time_now = time();
            // 获取运势相关数据
            $revive_day = null;
            try
            {
                $ver = Util::CheckAppVersion('2.9.4') === '小' ? 1 : 3;
                $fortune_cache = (new Fortune())->fortuneDayHomeData($this->user['rid'], $time_now, $ver);
                // 将今日运势图片替换为新图标
                $new_icon = explode('/', $fortune_cache['revive_day']['icon_url']);
                array_splice($new_icon, 5, 0, ['v3']);
                $fortune_cache['revive_day']['icon_url'] = implode('/', $new_icon);
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $this->user['id'] . ']' . $e->getMessage(), 'error');
                return show(0, '服务异常，请稍后再试~', '');
            }
            $data = [
                'week' => $this->weekDay[date('w', $time_now)],
                'date' => date('m.d', $time_now),
                'name' => $fortune_cache['revive_day']['name'],
                'star_level' => $fortune_cache['revive_day']['star_level'],
                'icon_url' => $fortune_cache['revive_day']['icon_url'],
                'list' => [
                    [
                        'name' => $fortune_cache['fortune_list'][0]['name'],
                        'score' => $fortune_cache['fortune_list'][0]['score'],
                        'color' => $fortune_cache['fortune_list'][0]['color']
                    ],
                    [
                        'name' => $fortune_cache['fortune_list'][1]['name'],
                        'score' => $fortune_cache['fortune_list'][1]['score'],
                        'color' => $fortune_cache['fortune_list'][1]['color']
                    ],
                    [
                        'name' => $fortune_cache['fortune_list'][2]['name'],
                        'score' => $fortune_cache['fortune_list'][2]['score'],
                        'color' => $fortune_cache['fortune_list'][2]['color']
                    ],
                    [
                        'name' => $fortune_cache['fortune_list'][4]['name'],
                        'score' => $fortune_cache['fortune_list'][4]['score'],
                        'color' => $fortune_cache['fortune_list'][4]['color']
                    ],
                    [
                        'name' => $fortune_cache['fortune_list'][6]['name'],
                        'score' => $fortune_cache['fortune_list'][6]['score'],
                        'color' => $fortune_cache['fortune_list'][6]['color']
                    ],
                    [
                        'name' => $fortune_cache['fortune_list'][8]['name'],
                        'score' => $fortune_cache['fortune_list'][8]['score'],
                        'color' => $fortune_cache['fortune_list'][8]['color']
                    ],
                ],
            ];
            return show(200, '请求成功', $data);
        }

        if ($app_type === 'android')
        {
            return show(200, '请登录查看运势', ['hint' => '请登录', 'hint1' => '请登录查看运势']);
        }
        return show(0, '请登录查看运势', ['hint' => '请登录']);
    }

    /**
     * 日运宜忌小组件接口
     */
    public function dayLuckyForbid()
    {
        if (!$this->user)
        {
            return show(config('code.error'), '请登录查看内容', [
                'hint' => '未登录'
            ]);
        }

        if ($this->user['rid'])
        {
            $time = strtotime(date('Y-m-d'));

            $map = ['time' => $time, 'rid' => $this->user['rid'], 'uid' => $this->user['id']];
            // $data = (new FortuneCache())->getDetailFortune($map);
            $data = (new \app\common\cachemodel\FortuneCache())->getDayFortune($map, 2);

            $date = date('m.d');
            $week = date('w');
            $w = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

            return show(config('code.success'), '请求成功', [
                'date' => $date,
                'week' => $w[$week],
                'lucky_names' => $data['lucky_name'],
                'forbid_names' => $data['forbid_name'],
                'hint' => '',
                'has_rid' => 1,
            ]);
        } else
        {
            return show(config('code.success'), '请求成功', [
                'date' => '',
                'week' => '',
                'lucky_names' => '',
                'forbid_names' => '',
                'hint' => '点击前往添加档案',
                'has_rid' => 0,
            ]);
        }
    }

    /**
     * 日运幸运元素小组件接口
     */
    public function daySymbol()
    {
        if (!$this->user)
        {
            return show(config('code.error'), '请登录查看内容', [
                'hint' => '未登录'
            ]);
        }

        if ($this->user['rid'])
        {
            $time = strtotime(date('Y-m-d'));

            $map = ['time' => $time, 'rid' => $this->user['rid'], 'uid' => $this->user['id']];
            // $data = (new FortuneCache())->getDetailFortune($map);
            $data = (new \app\common\cachemodel\FortuneCache())->getDayFortune($map, 2);

            $luckySymbol = [];
            $t = [
                '幸运色' => 1,
                '幸运方' => 2,
                '幸运星' => 3,
                '幸运数' => 4,
            ];
            foreach ($data['lucky_symbol'] as $datum)
            {
                $s = mb_substr($datum['name'], 0, 3);

                $luckySymbol[] = [
                    'name' => $datum['name'],
                    'icon_url' => $datum['icon_url'],
                    'type' => $t[$s] ?? 0,
                ];
            }

            return show(config('code.success'), '请求成功', [
                'data' => $luckySymbol,
                'hint' => '',
                'has_rid' => 1
            ]);
        } else
        {
            return show(config('code.success'), '请求成功', [
                'data' => [],
                'hint' => '点击前往添加档案',
                'has_rid' => 0,
            ]);
        }
    }

    /**
     * 幸运星小组件接口
     */
    public function luckyPlanet()
    {
        if (!$this->user)
        {
            return show(config('code.error'), '请登录查看内容', [
                'hint' => '未登录'
            ]);
        }
        $date = date('Ymd');

        $cacheKey = 'component:lucky_planet:' . $this->user['id'] . ':' . $date;
        $goddessWord = Cache::get($cacheKey, false);
        if (!$goddessWord)
        {
            if ($this->user['rid'])
            {
                $time = strtotime(date('Y-m-d'));

                $map = ['time' => $time, 'rid' => $this->user['rid'], 'uid' => $this->user['id']];
                // $data = (new FortuneCache())->getDetailFortune($map);
                $data = (new \app\common\cachemodel\FortuneCache())->getDayFortune($map, 2);

                $goddessWord = $data['goddess_list']['tips'];

                Cache::set($cacheKey, $goddessWord, 86400);
            } else
            {
                $fortuneConfigs = config('fortune');
                $wordData = $fortuneConfigs['word_tips'][array_rand($fortuneConfigs['word_tips'], 1)] ?? current($fortuneConfigs['word_tips']);
                $goddessWord = $wordData['tips'];

                Cache::set($cacheKey, $goddessWord, 86400);
            }
        }

        $luckyInfo = (new AppUserLuckyInfo())->IndexGetUserLuckyInfo($this->user['id']);
        $userLuckyChangeRecordModel = new AppUserLuckyChangeRecord();
        $luckyTaskRecordModel = new AppLuckyTaskRecord();
        $signInInfo = $userLuckyChangeRecordModel->getUserSignInfoByToday($this->user['id'], $date);
        if ($signInInfo['num'] < $luckyTaskRecordModel->MaxSignInNum)
        {
            $status = 1;
            $t = $signInInfo['time'] + $luckyTaskRecordModel->SignInInterval - $this->request->time();
            $lastTime = $t > 0 ? $t : 0;
        } else
        {
            $status = 0;
            $lastTime = 0;
        }

        return show(config('code.success'), '请求成功', [
            'have_num_title' => $luckyInfo['lucky_num'] . '颗幸运星',
            'status' => $status === 1 && $lastTime === 0 ? 1 : 0,
            'goddess_word' => $goddessWord,
        ]);
    }

    /**
     * 日历小组件接口
     */
    public function astroCalendar()
    {
        $date = date('Y-m');
        $timezone = 8;

        $astroChangeData = (new AstroChangeModel())->getChangeMonthList($date, $timezone);

        $planetsData = config('astrolog.planets_name');
        $signsData = config('astrolog.sign_name');
        $data = [];
        foreach ($astroChangeData as $item)
        {
            $type = 3;
            switch ($item['type'])
            {
                case 1:
                    if ((int)$item['pid'] === 0)
                    {
                        $type = 1; // 太阳换座
                    }
                    $text = explode('|', $planetsData[$item['pid']])[2] . explode('|', $signsData[$item['in_sign_id']])[2];
                    break;
                case 2:
                    $text = explode('|', $planetsData[$item['pid']])[2] . ((int)$item['speed'] === 1 ? '顺' : '逆');
                    break;
                case 3:
                    $text = '日食';
                    break;
                case 4:
                    $text = '月食';
                    break;
                case 5:
                    $type = 2; // 星月
                    $text = '新月';
                    break;
                case 6:
                    $text = '满月';
                    break;
                default:
                    $text = '';
                    break;
            }

            if ($text)
            {
                $time = gmdateModify('Y-m-d H:i:s', strtotime($item['time']), 0, $timezone, false); // 转换回该时区时间
                $day = date('d', $time);

                if ($type === 1)
                {
                    $key = 0;
                } elseif ($type === 2)
                {
                    $key = 1;
                } else
                {
                    $key = $time;
                }
                $data[$day][$key] = [
                    'text' => $text
                ];
            }
        }

        $astroChangeModel = new AstroChangeModel();
        // 获取星象变动数据 正在进行中的星象
        $underwayAstro = $astroChangeModel->getChangeDayList(date('Y-m-d'), $timezone);
        $des = '';
        if ($underwayAstro['resData'])
        {
            $rd = current($underwayAstro['resData']);
            $des = $rd['time'] . ' ' . $rd['astro_text'];
        }
        $resData = [
            'date' => date('Y/m'),
            'des' => $des,
            'astro' => [],
            'birthday' => []
        ];

        foreach ($data as $day => $datum)
        {
            ksort($datum);
            $resData['astro'][] = [
                'date' => $day,
                'desc' => current($datum)['text']
            ];
        }

        $recodeData = (new Recode())->userBirthMonthList($this->user, $date, $timezone);
        $tmpArr = [];
        $dateArr = explode('-', $date);//客户端的时间
        $year = current($dateArr);
        //判断客户端的年份是否是闰年
        $is_bissextile = is_bissextile($year);
        foreach ($recodeData as $k => $item)
        {
            $recodeTime = (int)$item['month'] . (int)$item['day'];//档案时间
            if (in_array($recodeTime, $tmpArr))   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            {
                unset($recodeData[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
            } else
            {
                //若客户端当前是平年，则2月29的生日不反回
                if (!$is_bissextile && $item['month'] == 2 && $item['day'] == 29)
                {
                    continue;
                }
                $tmpArr[] = $recodeTime;
                $resData['birthday'][] = [
                    'date' => $item['day'],//客户端年 + 档案月日
                    'type' => $item['type']
                ];  //将不同的值放在该数组中保存
            }
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 话题小组件接口
     */
    public function goddessArea()
    {
        $data = (new GoddessArea())->getHomeThemeData();

        return show(config('code.success'), '请求成功', $data);
    }
}
